<template>
  <!-- 第三方充值订单 -->
  <div class="app-container">
    <div class="app-wrap">
      <search-table ref="table" :table-loading="listLoading" :table-data="orderDataList" @query="getTopOrderList(true)" @reset="refresh">
        <template v-slot:row>
          <el-form-item label="渠道:" label-width="50px">
            <el-select v-model="listQuery.agent_id" placeholder="请选择渠道" filterable >
              <el-option label="全部" value="" ></el-option>
              <el-option :label="'【'+item.value+'】'+item.label" :value="item.value" v-for="(item, index) in channelData" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="marginR20">
            <el-select v-model="listQuery.type" filterable placeholder="请选择类型">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in conditionData" :key="index"></el-option>
            </el-select>
            <el-input class="width200" type="text" v-model="listQuery.a_chat_remark" clearable placeholder="请输入数值"  />
          </el-form-item>
          <el-form-item>
            <el-select v-model="listQuery.time" filterable placeholder="请选择时间类型">
              <el-option label="创建时间" value="start_time"></el-option>
              <el-option label="订单完成时间" value="end_time"></el-option>
            </el-select>
            <el-date-picker is-range v-model="listQuery.dateTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" 
            end-placeholder="结束日期" class="full-width-input time-box" :default-time="['00:00:00', '23:59:59']" :clearable="false"></el-date-picker>
          </el-form-item>
          <el-form-item class="marginR20"  label="第三方订单号:"  label-width="120px">
            <el-input type="text" v-model="listQuery.third_order_num" clearable placeholder="请输入第三方订单号查询" style="width:280px"/>
          </el-form-item>
          <el-form-item label="充值渠道:" label-width="80px">
            <el-select v-model="listQuery.channel_id" clearable filterable placeholder="请选择充值渠道">
              <el-option label="全部" :value="0">全部</el-option>
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in paymentChannelData" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="支付状态:" label-width="80px" class="marginR20">
            <el-select v-model="listQuery.order_status" clearable filterable placeholder="请选择订单状态">
              <el-option label="全部" :value="-1">全部</el-option>
              <el-option label="未支付" :value="0">未支付</el-option>
              <el-option label="成功" :value="1">成功</el-option>
              <el-option label="失败" :value="2">失败</el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="marginR20"  label="商品ID:"  label-width="60px">
            <el-input type="number" v-model="listQuery.goods_id" clearable placeholder="请输入商品ID"/>
          </el-form-item>
          
        </template>
        <template v-slot:actions>
          <div class="statistic flexDetween">
            <div class="flex">
              <el-button type="info" size="mini" icon="el-icon-refresh" @click="getTopOrderList">刷新</el-button> 
              <el-button class="marginL20 marginR20" type="success" size="mini" icon="el-icon-wallet" @click="isShowTotalsDetails=!isShowTotalsDetails,getTotalOrderList()">统计</el-button>
              <div class="flex" v-show="isShowTotalsDetails" style="height:36px">
                <p> 充值订单总额：<span class="colorGre">{{ totalForm.all_money }}</span></p>
                <p> 充值订单笔数：<span class="colorGre">{{ totalForm.all_count }}</span></p>
                <p> 充值成功总额：<span class="colorYe">{{ totalForm.all_success_money }}</span></p>
                <p> 充值成功笔数：<span class="colorYe">{{ totalForm.all_success_count }}</span></p>
              </div>
            </div>
            <el-button type="primary" size="mini" icon="el-icon-download" :disabled="!orderDataList.length"  @click="getExport">导出</el-button>
          </div>
        </template>
        <template>
          <el-table-column align="center" type="index" width="50">
            <template slot-scope="scope">
              <el-radio v-model="scope.row.isChecked" :label="true" @change="handleCurrentChange(scope.row)">{{ '' }}</el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="channel_name" label="充值渠道" align="center" width="200" />
          <el-table-column prop="order_num" label="订单号" align="center" width="200" show-overflow-tooltip/>
          <el-table-column prop="user_id" label="用户ID" align="center" width="120">
            <template slot-scope="scope">
              <span class="item_details" @click="isShowUserDetails = true,checkedItem = scope.row">{{ scope.row.user_id }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="agent_id" label="渠道名" align="center" width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-show="scope.row.agent_id">【{{scope.row.agent_id}}】{{ $public.channelLabel(scope.row.agent_id) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" align="center" width="180" />
          <el-table-column prop="updated_at" label="修改时间" align="center" width="180" />
          <el-table-column prop="third_order_num" label="第三方订单号" align="center" width="240" show-overflow-tooltip/>
          <el-table-column prop="order_status" label="订单状态" align="center" width="120">
            <template slot-scope="scope">
              <el-tag :type="orderType(scope.row.order_status)">{{ orderStatus(scope.row.order_status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="initiated_amount" label="订单发起金额" align="center" width="150" />
          <el-table-column prop="pay_money" label="实际支付金额" align="center" width="150" />
          <el-table-column prop="recharge_reward" label="充值筹码" align="center" width="150" />
          <el-table-column prop="send_reward" label="赠送筹码" align="center" width="150" />
          <el-table-column prop="is_first_pay" label="是否是首次充值" align="center" width="150">
            <template slot-scope="scope">
              <el-tag type="info" v-show="!scope.row.is_first_pay">否</el-tag>
              <el-tag type="success" v-show="scope.row.is_first_pay">是</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="service_notice_status" label="服务端通知状态" align="center" width="150">
            <template slot-scope="scope">
              <el-tag :type="serviceStatusType[scope.row.service_notice_status]"
                disable-transitions
              >{{ serviceStatus(scope.row.service_notice_status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="goods_id" label="商品" align="center" width="180">
            <template slot-scope="scope">
              {{ goodsLabel(scope.row.goods_id) }}【{{ scope.row.goods_id }}】
            </template>
          </el-table-column>
          <el-table-column prop="fail_reason" label="失败原因" align="center" width="200" />
          <el-table-column prop="user_created_at" label="用户注册时间" align="center" width="180" />
          <el-table-column align="center" fixed="right" prop="operation" label="操作" width="150">
            <template slot-scope="scope">
              <el-button :disabled="scope.row.service_notice_status!=3?true:false" v-permission="'payOrder.edit'" size="mini" type="primary" @click.stop="sendOrder(scope.row)">再次通知</el-button>
            </template>
          </el-table-column>
        </template>
        <template v-slot:footer>
          <pagination :total="currentTotal" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getTopOrderList" />
        </template>
      </search-table>
    </div>
    <el-dialog :visible.sync="isShowDetails" v-if="isShowDetails" title="订单补分" width="50%" :before-close="handleClose" top="200px" :close-on-click-modal="false">
      <div>
        <el-input placeholder="请输入理由" type="textarea" :rows="3" v-model="reason" clearable></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="medium" @click="editReason">确 定</el-button>
      </span>
    </el-dialog>
    <user-details :show="isShowUserDetails" :data="checkedItem" @onHideDetails="handleClose" />
  </div>
</template>

<script>
import { throttle } from '@/utils/index'
import {
  getTopOrder,
  getTotalOrders,
  editTopOrder,
  orderServer,
  paymentChannel,
  exportOrder
} from '@/api/order'
import { 
  ORDER_STATUS,
  GAME_TYPE
 } from '@/utils/enum'
import SearchTable from '@/components/SearchTable'
import UserDetails from '@/views/userManage/user/page-details.vue'
export default {
  name: 'threeWay',
  components: {
    SearchTable,
    UserDetails
  },
  data () {
    return {
      GAME_TYPE,
      ORDER_STATUS,
      channelData: this.$store.state.commonState.channelDataArray,
      goodsAllData:this.$store.state.commonState.goodDataArray,
      conditionData:[
        { label:'用户ID', value:'user_id'},
        { label:'订单号', value:'order_num'},
      ],
      orderStatusData:[
        { label:'未支付', value:0, type:'warning' },
        { label:'支付成功', value:1, type:'success' },
        { label:'支付失败', value:2, type:'info' },
        { label:'未支付', value:0, type:'warning' },
      ],
      serviceStatusData:[
        { label:'默认', value:0, type:'info'},
        { label:'待通知', value:1, type:'info'},
        { label:'通知成功', value:2, type:'success'},
        { label:'通知失败', value:3, type:'info'},
      ],
      serviceStatusType:{
        1:'info',
        2:'success',
        3:'info',
        0:'info'
      },
      totalForm:{
        all_count: '',// 充值订单笔数
        all_money: '',// 充值订单总额
        all_success_count: '',// 充值成功笔数
        all_success_money: '',// 充值成功金额
      },
      isShowDetails: false,
      isShowUserDetails: false,
      isShowTotalsDetails: false,
      reason:'',
      checkedItem: null,
      listLoading: true,
      orderDataList: [],
      listQuery: {
        page: 1,
        size: 50,
        type: 'user_id',
        time: 'start_time',
        a_chat_remark:'',
        user_id: '',
        order_num: '',
        agent_id: '',
        goods_id:'',
        third_order_num:'',
        order_status: -1,
        channel_id:0,
        dateTime: [this.$public.getDateWeek('s',0)+' 00:00:00',this.$public.getDateWeek('e',0)+' 23:59:59'],
        start_time: '',
        end_time: '',
        update_time_start: '',
        update_time_end: '',
      },
      currentTotal: 0,
      pathDataList: [],
      paymentChannelData:[],
    }
  },
  created () {
    // this.getPaymentChannel()
  },
  activated(){
    this.channelData=this.$store.state.commonState.channelDataArray
    this.goodsAllData=this.$store.state.commonState.goodDataArray
    this.getPaymentChannel()
  },
  methods: {
    // 查询三方订单
    async getTopOrderList (query) {
      let that = this,params=that.listQuery;
      if(query && !query.page){
        params.page=1
        params.size=50
      }
      that.orderDataList = [];
      that.checkedItem = null;
      // 订单号
      if(params.type=='order_num'){
        params.order_num=params.a_chat_remark
        params.user_id=''
      }
      // 用户ID
      if(params.type=='user_id'){
        params.user_id=params.a_chat_remark
        params.order_num=''
      }
      if (params.dateTime && params.dateTime[0] && params.dateTime[1]) {
        // 开始时间
        if(params.time=='start_time'){
          params.start_time = that.$public.standardDate(params.dateTime[0])
          params.end_time = that.$public.standardDate(params.dateTime[1])
          params.update_time_start = ''
          params.update_time_end = ''
        }else{
          params.update_time_start = that.$public.standardDate(params.dateTime[0])
          params.update_time_end = that.$public.standardDate(params.dateTime[1])
          params.start_time = ''
          params.end_time = ''
        }
      }
      const response = await getTopOrder(params)
      if (response.code == 1) {
        if(response.data.list){
          response.data.list.forEach(item => {
            item.isChecked = false
            item.recharge_reward=that.$public.mathNumberDivideWan(item.recharge_reward)
            item.send_reward=that.$public.mathNumberDivideWan(item.send_reward)
            item.initiated_amount=that.$public.mathNumberDivideWan(item.initiated_amount)
            item.pay_money=that.$public.mathNumberDivideWan(item.pay_money)
          })
          that.orderDataList = response.data.list
          that.currentTotal = response.data.total
        }
      }else{
        that.$message.error(response.msg)
      }
      that.listLoading = false
    },
    // 充值渠道
    async getPaymentChannel(){
      let that = this;
      that.paymentChannelData=[]
      const response = await paymentChannel({})
      if (response.code == 1) {
        if (response.data) {
          for (const key in response.data) {
            if(typeof(response.data[key])=='string'){
              that.paymentChannelData.push({label:response.data[key],value:key})
            }
          }
          that.getTopOrderList();
        }
      }else{
        that.$message.error(response.msg)
      }
    },
    // 充值订单合计
    getTotalOrderList () {
      let that = this;
      if(!that.isShowTotalsDetails) return
      getTotalOrders(that.listQuery).then(res => {
        if (res.code == 1) {
          res.data.all_money=that.$public.mathNumberDivideWan(res.data.all_money)
          res.data.all_success_money=that.$public.mathNumberDivideWan(res.data.all_success_money)
          that.totalForm=res.data
        }
      }).catch((error) => {
        that.$message.error(error.msg)
      })
    },
    // 导出
    getExport(){
      let that = this,serveUrl=process.env.VUE_APP_BASE_API.substring(0,process.env.VUE_APP_BASE_API.length-6);
      exportOrder(that.listQuery).then(res => {
        if (res.code == 1) {
          window.open(serveUrl+res.data)
        }
      }).catch((error) => {
        that.$message.error(error.msg)
      })
    },
    // 失败订单 再次通知
    sendOrder(row){
      let that = this;
      that.$confirm('是否再次通知服务端?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        orderServer({
        order_num: row.order_num, //订单号
      }).then(res => {
        if (res.code == 1) {
          that.$message.success(res.msg)
          that.getTopOrderList()
        }
      }).catch((error) => {
        that.$message.error(error.msg)
      })
      }).catch(() => {});
    },
    // 订单补分
    orderBonus(row){
      this.handleCurrentChange(row)
      this.isShowDetails=true
    },
    editReason(){
      let that = this;
      editTopOrder({
        order_num: that.checkedItem.order_num, //订单号
        reason: that.reason //变更理由
      }).then(res => {
        if (res.code == 1) {
          that.$message.success(res.msg)
          that.handleClose()
          that.getTopOrderList()
        }
      }).catch((error) => {
        that.$message.error(error.msg)
      })
    },
    // 关闭
    handleClose(){
      this.isShowDetails=false
      this.isShowUserDetails=false
      
      this.reason=''
    },
    // 商品的值
    goodsLabel(cellValue){
      return (this.goodsAllData.find((item) => item.value === cellValue)?.label || "");
    },
    // 游戏类型展示
    orderStatus(cellValue){
      return (this.orderStatusData.find((item) => item.value === cellValue)?.label || "-");
    },
    orderType(cellValue){
      return (this.orderStatusData.find((item) => item.value === cellValue)?.type || "-");
    },
    // 服务端
    serviceStatus(cellValue){
      return (this.serviceStatusData.find((item) => item.value === cellValue)?.label || "-");
    },
    // 选择表格数据
    handleCurrentChange (val) {
      this.checkedItem = val
      this.orderDataList.map(item => {
        if (item.id === val.id) {
          item.isChecked = true
        } else {
          item.isChecked = false
        }
      })
    },
    // 刷新
    refresh:throttle(function () {
      let that = this;
      that.listQuery = {
        page: 1,
        size: 50,
        type: 'user_id',
        time: 'start_time',
        a_chat_remark:'',
        user_id: '',
        order_num: '',
        agent_id: '',
        goods_id:'',
        third_order_num:'',
        order_status: -1,
        channel_id:0,
        dateTime: [this.$public.getDateWeek('s',0)+' 00:00:00',this.$public.getDateWeek('e',0)+' 23:59:59'],
        start_time: '',
        end_time: '',
        update_time_start: '',
        update_time_end: '',
      }
      that.totalForm={
        all_count: '',
        all_money: '',
        all_success_count: '',
        all_success_money: '',
      }
      that.getTopOrderList();
    }, 2000),
  }
}
</script>

<style lang="scss" scoped>

</style>
